import type { Metadata } from "next";
import { request } from "@/utils/request";
import { DataResponse, ArticleInfo } from "@/type";
import { renderMarkdown } from "@/utils/mdConvertHTML";
import MDView from "./MDView";
import TocCatalog from "./TocCatalog";
import Comments from "./Comments";
import { convertTimeZone } from "@/utils/operateTime";

type Props = {
  params: Promise<{
    articleId: number;
  }>;
};

async function getArticleInfo(articleId: number): Promise<ArticleInfo> {
  const res = await request<DataResponse<ArticleInfo>>(
    `/articleInfo/${articleId}`,
    {
      next: { revalidate: 60 },
      cache: "force-cache",
    }
  );
  if (!res) {
    throw new Error("获取文章失败");
  }
  return res.data;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { articleId } = await params;
  const articleInfo = await getArticleInfo(articleId);
  return {
    title: `${articleInfo.title}-Reindeer の Room`,
    description:
      articleInfo.synopsis ??
      "ReindeerBlog--使用 NextJS NestJS 现代技术栈构建的易于 SEO 的博客系统",
  };
}

export default async function Page({ params }: Props) {
  const { articleId } = await params;
  const articleInfo = await getArticleInfo(articleId);
  const { contentHTML, tocCatalogHTML } = await renderMarkdown(
    articleInfo.content
  );

  return (
    <div className="md:w-[60%] w-screen mx-auto">
      <div className="flex justify-center gap-10 mt-10 px-4 relative">
        {/* 左侧目录 */}
        <aside className="w-64 shrink-0 sticky top-[160px] h-fit self-start py-4 rounded-lg shadow-xl bg-primary-card max-h-[50vh] overflow-auto hidden lg:block">
          <TocCatalog tocCatalogHTML={tocCatalogHTML} />
        </aside>

        {/* 右侧正文区域 */}
        <main className="w-full">
          <div className="text-3xl md:text-5xl mb-5">{articleInfo.title}</div>
          <div className="mb-8 flex justify-end text-sm md:text-lg">
            📅 {convertTimeZone(articleInfo.create_time).split(" ")[0]}
            (更新于{convertTimeZone(articleInfo.update_time).split(" ")[0]}
            )&emsp;👀
            {articleInfo.page_view} Views&emsp;⏳ 预计阅读时长 ?? 分钟
          </div>
          <MDView contentHTML={contentHTML} />
        </main>
      </div>
      <div className="mt-10 mb-5 md:mb-10 p-1 md:p-5 rounded-lg bg-primary-card shadow-xl text-base md:text-lg">
        <span className="text-xl md:text-3xl">评论区</span>
        <span className="text-stone-400">暂时只支持 GitHub 账号登陆评论</span>
        <div className="m-3 md:m-10">
          <Comments articleId={articleId} />
        </div>
      </div>
    </div>
  );
}
